package com.itheima.reggie.controller;

import com.github.pagehelper.PageHelper;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private HttpSession session;

    @Autowired(required = false)
    private EmployeeService employeeService;



    /**
     * 登录功能
     * @param employee
     * @return
     */
    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee){
        R<Employee> result = employeeService.login(employee);
        if (result.getCode() == 1){
            session.setAttribute("Employee",result.getData().getId());
            return result;
        }else {
            return result;
        }
    }

    /**
     * 退出功能
     * @return
     */
    @RequestMapping("/logout")
    public R<String> logout(){
        session.invalidate();
        return R.success("退出成功");
    }

    /**
     * 保存员工功能
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        Long employeeID = (Long) session.getAttribute("Employee");
        employee.setCreateUser(employeeID);
        employee.setUpdateUser(employeeID);
        employeeService.save(employee);

        return R.success("保存成功");
    }


    /**
     * 修改员工功能
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee){
        Long userID = (Long) session.getAttribute("Employee");
        employee.setUpdateUser(userID);
        employeeService.update(employee);

        return R.success("修改成功");
    }

    /**
     * 根据姓名查看功能
     * @param page 当前页
     * @param pageSize 显示数据的数量
     * @param name 姓名
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10")  Integer pageSize, String name){
        Page<Employee> employeePage = employeeService.findByName(page, pageSize, name);
        return R.success(employeePage);
    }

    /**
     * 根据ID查找功能
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable("id") Long id){
        R<Employee> employee = employeeService.findById(id);
        return employee;
    }

}
